package com.gserver.netty.coder;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gserver.netty.domain.Message;

public class ObjectDecoder extends FrameDecoder {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		log.debug("ObjectDecoder.decode()" + "threadId="
				+ Thread.currentThread().getId());
		if (buffer.readableBytes() < 4) {
			return null;
		}
		buffer.markReaderIndex();
		int needbytes = buffer.readInt();
		log.debug("needbytes:" + needbytes);
		if (buffer.readableBytes() < needbytes - 4) {
			buffer.resetReaderIndex();
			return null;
		}
		short handle = buffer.readShort();
		short cmd = buffer.readShort();
		byte[] data = new byte[needbytes - 4];
		buffer.readBytes(data);
		Message msg = new Message(handle, cmd, data, ctx);

		return msg;
	}
}
